﻿#include "recbox.h"
#include "ui_recbox.h"
#include "recboxitem.h"
#include <QJsonObject>

RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(1),
    col(4)
{
    ui->setupUi(this);

    connect(ui->btUp, &QPushButton::clicked, this, &RecBox::on_btUp_clicked);
    connect(ui->btDown, &QPushButton::clicked, this, &RecBox::on_btDown_clicked);
}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray data, int row) {
    if (row == 2) {
        this->row = row;
        col = 8;
    }
    else {
        ui->recListDown->hide();
    }

    imageList = data;
    currentIndex = 0;
    count = imageList.size() / col;
    //在Rec中添加RecItem
    createRecBoxItem();
}

void RecBox::createRecBoxItem() {
    //换页时需要清除，之前的元素
    QList<RecBoxItem*> recUpList = ui->recListUp->findChildren<RecBoxItem*>();
    for (auto upList : recUpList) {
        ui->recListUpHLayout->removeWidget(upList);
        delete upList;
    }
    QList<RecBoxItem*> recDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for (auto DownList : recDownList) {
        ui->recListDownHLayout->removeWidget(DownList);
        delete DownList;
    }

    int index = 0;
    for (int i = currentIndex * col; i < col + currentIndex * col; i++, index++) {
        RecBoxItem* item = new RecBoxItem();

        QJsonObject obj = imageList[i].toObject();
        item->setRecText(obj.value("text").toString());
        item->setRecImage(obj.value("path").toString());

        if (index >= col / 2 && row == 2) {
            ui->recListDownHLayout->addWidget(item);
        }
        else {
            ui->recListUpHLayout->addWidget(item);
        }
    }
}

void RecBox::on_btUp_clicked() {
    currentIndex--;
    if (currentIndex < 0) {
        currentIndex = count - 1;
    }
    createRecBoxItem();
}

void RecBox::on_btDown_clicked() {
    currentIndex++;
    if (currentIndex >= count) {
        currentIndex = 0;
    }
    createRecBoxItem();
}